package top.guxx.mall.job;

import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import top.guxx.mall.config.RedisService;
import top.guxx.mall.constants.Constants;
import top.guxx.mall.service.IOrderService;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;

/**
 * @Author：Guxx
 * @Description：关闭超时订单
 * @Date：2025/2/23 1:13
 * @Filename：TimeOutCloseOderJob
 */
@Slf4j
@Component
public class TimeOutCloseOrderJob {

    @Resource
    private IOrderService orderService;

    @Resource
    private RedisService redisService;


    @Scheduled(cron = "0 0/10 * * * ?")
    public void exec(){
        try {
            List<String> orders = orderService.queryNoPayNotifyOrder();
            if (orders == null || orders.isEmpty()){
                return;
            }
            //恢复库存
            for (String orderId : orders) {
                orderService.changeOrderClose(orderId);
                Map<Object, Object> map = redisService.getMap(orderId);
                for (Object o : map.keySet()) {
                    redisService.incr(Constants.RedisKey.STOCK.getCode() + o.toString(),Long.parseLong(map.get(o).toString()));
                }
                log.info("关闭超时订单任务扫描，关闭订单 订单ID: {}, 恢复库存: {}", orderId, map);
            }
        }catch (Exception e){
            log.error("定时任务，超时15分钟订单关闭失败", e);
        }
    }
}
